<?php
/**
  * The Class for the controller component of the application
  *
  */

class AjaxController extends Zend_Controller_Action
{
    /**
     * The class constructor for the derived class
     *
     */

    private $_registry;
    private $_redirector;
    private $_db;
    private $_user;

    function init()
    {
        $this->_redirector = $this->_helper->getHelper('Redirector');
        /*
         * First check to ensure that the request is a valid AJAX query
         * by check the headers for XmlHttp request
         */

        if(!$this->getRequest()->isXmlHttpRequest())
        {
            $this->_redirector->gotoRoute(array('action' => 'error'), 'index');
        }

        //Initiate the registry object
        $this->_registry = Zend_Registry::getInstance();
        $this->_db = $this->_registry->get('db');

        //Load the user's session stored
        $session = new Zend_Session_Namespace('User');
		if( isset($session->user) )
		{
			//Get an upto date record of the current user
			$Users = new Users();
			$this->_user = $Users->getUserById($session->user->uid);			
		}
		else
		{
			$this->_user = null;
		}
		
		// Create a record in the registry for global access to fresh user goodness, whether null or useful
		$this->_registry->user = $this->_user;
		
        //Setup the ebay client by passing the uid through static method
        Ebay_Client::setUid($this->_user->uid);

        //Disable layouts
        $this->_helper->layout->disableLayout();

        if(!$this->_user)
        {
            $this->_forward('needsLogin');
        }
    }

    function indexAction()
    {

    }

    //A user is needed to be logged in to make an ajax request
    function needLoginAction()
    {

    }

    function removeimageAction()
    {
        $data = $this->_request->getPost('json');
        $data = Zend_Json::decode($data);

        if(isset($data['pid']))
        {
            $Images = new Images();
            $image = $Images->fetchRow($Images->select()->where('pid = ?', $data['pid']));

            $Items = new Items();
            $item = $Items->fetchRow($Items->select()->where('id = ?', $image->id));
            $path =  getcwd()."/host/" . $image->filename;

            if($item->gallery == $image->pid)
            {
                $item->gallery = null;
                $item->save();
            }

            if($image && $image->delete() && file_exists($path) && fclose($path) && unlink($path))
            {
                $this->view->data = array('status' => true);
            }
            else
            {
                $this->view->data = array('status' => false, 'message' => "The uploaded file couldn't be removed");
            }
        }
        elseif(isset($data['filename']))
        {
            $path = getcwd(). "/host/" . $data['filename'];
            if(file_exists($path) && fclose($path) && unlink($path))
            {
                $session = new Zend_Session_Namespace('Listing');
                foreach($session->images as &$image)
                {
                    if($image['filename'] == $data['filename'])
                    unset($image);
                }

                $this->view->data = array('status' => true);
            }
            else
            {
                $this->view->data = array('status' => false, 'message' => "The uploaded file couldn't be deleted");
            }
        }
        else
        {
            $this->view->data = array('status' => false, 'message' => "Incorrect parametres where passed");
        }
        $this->render('ajax');
    }

    function getImagesAction()
    {
        $id = $this->_request->getParam('arg1', false);

        if($id && is_numeric($id))
        {
            $Items = new Items();
            if(!$Items->getBasicItem($id))
            {
                $this->view->data = array('status' => false, 'message' => "The item doesn't belong to you");
                return;
            }

            // Load the images belonging to the item
            $Images = new Images();
            $images = $Images->fetchAll($Images->select()->where('id = ?', $id))->toArray();

            $this->view->data = array('status' => true, 'images' => $images);
        }
        else
        {
            $this->view->data = array('status' => false, 'message' => "An invalid item id was passed");
        }
        $this->render('ajax');
    }

    function saveImages($id)
    {
        // Upload any new images
        $Images = new Images();
        $session = new Zend_Session_Namespace('Listing');
        if(isset($session->images))
        {
            $images = $session->images;
            foreach($images as &$img)
            {
                $image = $Images->createRow();
                $image->id = $id;
                $image->filename = $img['filename'];
                $image->save();

                //Move the images from tmp to main directory
                rename(getcwd()."/host/tmp/{$image->filename}", getcwd()."/host/{$image->filename}");
            }
            $session->images = array();
        }
    }

    function getcategoryspecificsAction()
    {

        $cid = $this->_request->getParam('arg1', false);

        $validator = new Validate_Category();
        if($cid && $validator->isValid($cid))
        {
            $ebay = new Ebay_Client();
            $specifics = $ebay->getCategorySpecifics($cid);
            var_dump($specifics);
            $specifics = $specifics->CategoryItemSpecifics->ItemSpecifics;
/*
            $itemSpecifics = array();
            foreach($specifics as &$nameValue)
            {
                $key = $nameValue->NameValueList->Name;
                $itemSpecifics[$key] = $nameValue->NameValueList->Value;
            }*/
        }
        $this->render('ajax');
    }
	
	function getcategorydetailsAction()
	{
		$cid = $this->_request->getParam('arg1', false);
		$validator = new Validate_Category();
		if(!$validator->isValid($cid))
		{
			$this->view->data = array('status' => false, 'message' => 'An invalid category number was provided');
			return $this->render('ajax');
		}
		$ebay = new Ebay_Client();

		$features = $ebay->getCatgoryFeatures($cid, array('ListingDurations', 'ItemSpecificsEnabled'));
		$days;

		$durations = &$features->FeatureDefinitions->ListingDurations->ListingDuration;
		foreach($durations as $duration)
		{
			if($duration->attributes()->durationSetID == 1)
			{
				$days = $duration->Duration;
			}
		}
		//var_dump($features);
		$details = array('duration' => array(), 'specifics' => array());
		
		//Extract the duration from each string and store in the details array
		foreach($days as $str)
		{
			$time = substr($str, 5);
			$details['duration'][] = $time;
		}
		
		if($features->ItemSpecificsEnabled == 'Enabled')
		{
			// Get the category specifics  from the associated category ID
			$specifics = $ebay->getCategorySpecifics($cid);
			$specificsArray = &$specifics->CategoryItemSpecifics->ItemSpecifics->NameValueList; // A reference to the  itemspecifics
			foreach($specificsArray as $key)
			{
				$values = null;
				if(is_array($key->Value))
				{
					$values = array();
					foreach($key->Value as $value)
					{
						$values[] = $value;
					}
				}
				$details['specifics'][] = array('key' => $key->Name, 'values' => $values);
			}
			
			
		}
		$this->view->data = array('status' =>true, 'details' => $details);
		return $this->render('ajax');
	}
	
    function getcategoryAction()
    {
        $mode = $this->_request->getParam('arg1', '');
        $cid = $this->_request->getParam('arg2', 0);

        if($mode == 'cid' || $mode == 'pid')
        {
            if(is_numeric($cid))
            {
                $Categories = new Categories();
                $this->view->data = array('categories' => ($mode == 'cid') ? $Categories->getcategories($cid) : $Categories->getCategoryParents($cid));
                $this->render('ajax');
            }
            else
            {
                $this->view->data = array('status' => false, 'message' => "An invalid category id was passed");
            }
        }
    }
	
	function syncAction()
	{
		$ebay = new Ebay_Client();
		$result = $ebay->sync();
		
		if($result)
		{
			$Items = new Items();
			foreach($result as $id)
			{
				$listings[] = $Items->getItem($id);
			}
			
			$this->view->data = array('status' => true, 'listings' => $listings);
		}
		else
		{
			$this->view->data = array('status' => false);
		}
		return $this->render('ajax');
	}

    function createAction()
    {
        $job = $this->_request->getParam('arg1', false);
        $id = $this->_request->getParam('arg2', '');
        if($job)
        {
            switch($job)
            {
                case 'save':
                $result = $this->createListing();
                if($result)
				{
					$this->view->data = array('status' => true, 'listing' => $result);
				}
                return $this->render('ajax');				
                break;
                case 'submit':                
				$item = $this->createListing();
				
				if($item)
				{
					$data = $this->_request->getPost('json');
					$data = Zend_Json::decode($data);
					
					try
					{
						$result = $this->submitListing($item['id'], ( isset($data->confirm)) ? false : true);
					} catch (Ebay_Exception $e)
					{
						// An Exception Occured
						$this->view->data = array('status' => false, 'message' => $e->getMessage());
						return $this->render('ajax');
					}
				
					// If only verifying the submission
					if(!isset($data->confirm))
					{
						$this->view->data = array('status' => true, 'request' => 'validate', 'fees' => $result, 'listing' => $item);
					}
				}   
                return $this->render('ajax');
				
                break;
                case 'form':
                    //Clear the previous namespace
                    $session = new Zend_Session_Namespace('Listing');
                    $session->unsetAll();
					
					$this->view->user = $user;
                    return $this->render('create');
                break;
            }
        }
        else
        {
            $this->view->data = array('status' => false, 'message' => "An Invalid  request has been made");
        }

        $this->render('ajax');
    }

    
	
	
	/**
	 * Constructs  a Zend Filter Input chaing with the generic options for validating and filtering a listing
	 * @return Zend_Filter_Input
	 */
	function getValidator()
	{
		$filters = array(
        );

        $validators = array(
			'id' => array('Int'),
            'title' => array( array('NotEmpty', true),
                             array('StringLength', 3, 55),
                             'presence' => 'required', 'breakChainOnFailure' => true),
            'description' => array(array('NotEmpty', true), 'presence' => 'required', 'breakChainOnFailure' => true),
            'startPrice' => array(array('NotEmpty', true), 'Float', 'presence' => 'required', 'breakChainOnFailure' => true),
            'duration' => array(array('NotEmpty', true), 'Int', 'presence' => 'required', 'breakChainOnFailure' => true),
            'delivery' => array(array('NotEmpty', true), 'Float', 'presence' => 'required', 'breakChainOnFailure' => true),
            'cid' => array('Int', new Validate_Category(), 'presence' => 'required', 'breakChainOnFailure' => true),
            'payment' => array(new Validate_Payment()),
			'paypalAddress' => array('EmailAddress')
			);

        $options = array(
            'missingMessage' => "Field '%field%' is required",
        );

        return new Zend_Filter_Input($filters, $validators, $options);
	}
	
	/**
	 * Gets the json parameter from the request, decodes this and sets up an Zend Filter Input associated with validating and filtering a listing
	 * @return Zend_Filter_Input
	*/
    function validateListing()
    {
        $json = $this->_request->getPost('json', 'false');
        $json = Zend_Json::decode($json);

		if(!$json)
		{
			return false;
		}
		
        $input = $this->getValidator();
        $input->setData($json);
		
		return $input;
    }

	function saveListing($data, $new)
    {
        $Items = new Items();		
		if($new)
		{
			$item = $Items->createRow();
		}
		else
		{
			$item = $Items->getBasicItem($data['id']);
			// If the row couldn't be found or doens't belong to the user return an error;
			if(!$item)
			{
				$this->view->data = array(
					'status'  => false, 
					'message' => "The listing couldn't be found or doesn't belong to you.");
				return false;
			}
		}

        //Populate and remove some extra fields
        $data['uid'] = $this->_user->uid;		

		// Unserialise the details and then allow extra details skipped through validation, to be added.
		$data['details'] = isset($new) ? new StdClass() : unserialize($item->details);
		
		// Implode the array of payment options (if exists) into a comma seperated string
		$data['details']->paymentOptions = (!is_array($data['payment'])) ? $data['payment'] : implode(',', $data['payment']);
		
		if(is_array($data['payment']) && in_array('PayPal', $data['payment']) && isset($data['paypalAddress']))
		{
			$data['details']->paypalAddress = $data['paypalAddress'];
		}
		
		$data['details'] = serialize($data['details']);
		
		// Remove any keys not associated with the database
		unset($data['paypalAddress']);
		unset($data['payment']); //This is needed to be removed and is stored in a serialized field in the database instead
		
		if($item->setFromArray($data)->Save())
		{
			$this->saveImages($item->id);
		}
		else
		{
			$this->view->data = array('status' => false, "The listing couldn't be updated.");
			return false;
		}

		if($new)
		{
			// A status is always created with a new item row
	        $Status = new Status();
	        $status= $Status->createRow();

	        $date = new Zend_Date();
	        $status->created = $date->getIso();
	        $status->id = $item->id;
	        $status->status = 0;

	        $status->save();
		}

        // Return a fresh copy of the new item that has been created
        return $Items->getItem($item->id);
    }
	
	function removelistingsession()
    {
        //Clear the previous namespace
        $session = new Zend_Session_Namespace('Listing');
        if(isset($session->images))
        {
            foreach($session->images as $image)
            {
                $path = getcwd()."/host/tmp" . $image['filename'];
                if(file_exists($path))
                {
                    unlink($path);
                }
            }
        }

        $session->unsetAll();
    }
	
    function createListing()
    {
		// Get a Zend_Filter_Input with the data already loaded
        $input = $this->validateListing();
        if($input && $input->isValid())
        {
            $data = $input->getEscaped();

            //Override escaped for description
            //$data['description'] = $input->getEscaped('description');
			
            //Save the listing, second argument set to true to indicate new record
            return $this->saveListing($data, true);
        } 
		else 
		{
            $this->view->data = array('status' => false, 'errors' => $input->getMessages());
            return false;
        }
    }

    function editListing()
    {
		$input = $this->validateListing();
        if($input && $input->isValid())
        {
            $data = array();
            foreach($input->getUnescaped() as $key => $value)
            {
                $data[$key] = $value;
            }

            //Override escaped for description
            $data['description'] = $input->getEscaped('description');
			
            //Save the listing, second argument set to false to indicate editing a record
            return $this->saveListing($data, false);
        } 
		else 
		{
            $this->view->data = array('status' => false, 'errors' => $input->getMessages());
            return false;
        }
    }	
	
	/**
	 * Processes fees accordingly from calls such as ReviseItem, AddItem etc.
	 * @param SimpleXMLElement $response the XML contain the Fees Element
	 */
	function processFees($response)
	{
		$fees = array();
		$feeTotal = 0;
		foreach($response->Fees->Fee as $fee)
		{
			// Don't process any fees that aren't relevant.
			if( (float)$fee->Fee == 0)
			{ 
				continue; 
			}
			$fees[] = array((string) $fee->Name, (string) $fee->Fee);
		}
		
		return $fees;
	}
	
	function submitListing($id, $verify = true)
    {
        $Items = new Items();
        $item = $Items->getBasicItem($id)->toArray();

        $Images = new Images();
        $item['images'] = $Images->getById($item['id'])->toArray();

		// Create a new ebay client
        $ebay = new Ebay_Client();
		
        if($verify)
        {
            $response = $ebay->verifyAddItem($item);
			$fees = $this->processFees($response);
			
			return $fees;
        }
		else
		{
			$response = $ebay->addItem($item);
			$Status = new Status();
			$status = $Status->fetchRow($Status->select()->where('id = ?', $item['id']));
			
			//Format the data and times into strings
			$response->submitted = $response->submitted;
			$response->finishes = $response->finishes;
			
			$dbData = (array) $response; //Cast into an array so that the row can be updated.
			$dbData['status'] = 1; //Set the status of the Item to 1 i.e. submitted.
			
			$status->setFromArray($dbData)->Save();			
			return true;
		}
    }
	
	//########### 	ACTIONS ############//
    function editAction()
    {
        $job = $this->_request->getParam('arg1', false);
        $id = $this->_request->getParam('arg2', '');

        if($job)
        {
            switch($job)
            {
				case 'save':
                    $result = $this->editListing();
					if($result)
					{
						$this->view->data = array('status' => true, 'listing' => $result);
					}
					else
					{
						$this->view->data = array('status' => false, 'message' => "The listing couldn't be saved.");
					}
					
                    return $this->render('ajax');
                break;
                case 'submit':
                    $item = $this->editListing();
					if($item)
					{
						$data = $this->_request->getPost('json');
						$data = Zend_Json::decode($data);
						
						try
						{
							$result = $this->submitListing($item['id'], ( isset($data->confirm)) ? false : true);
						} catch (Ebay_Exception $e)
						{
							// An Exception Occured
							$this->view->data = array('status' => false, 'message' => $e->getMessage());
							return $this->render('ajax');
						}
						
						// If only verifying the submission
						if(!isset($data->confirm))
						{
							$this->view->data = array('status' => true, 'request' => 'validate', 'fees' => $result, 'listing' => $item);
						}
					}                    
                    //$this->view->data = $result;
                    return $this->render('ajax');
                break;
                case 'form':
				if(!Zend_Validate::is($id, 'Int'))
                {
					$this->view->data = array('status' => false, 'An invalid listing id was provided');
					return $this->render('ajax');
				}
				
				$Items = new Items();
                $item = $Items->getItem($id, $this->_user->uid);
				
				if(!$item)
				{
					$this->view->data = array('status' => false, "The listing couldn't be found or doesn't belong to you");
					return;
				}
				$this->removelistingsession();				

				$Categories = new Categories();
				$category = $Categories->fetchRow($Categories->select()->where('cid = ?', $item['cid']));

				$this->view->category = array('cid' => $category->cid, 'pid' => $category->pid, 'level' => $category->level);

				$this->view->item = $item;
				$this->view->user = $user;
				
				return $this->render('edit');
			}
			break;
		}
		$this->view->data = array('status' => false, 'message' => "An Invalid  request has been made");
        $this->render('ajax');
    }
	
	function relistAction()
	{
		$data = $this->_request->getPost('json', 'false');
        $data = Zend_Json::decode($data);
		
		if(!$data || !is_array($data) || !is_array($data['listings']))
		{			
			$this->view->data = array('status' => false, 'message' => "An Invalid request has been made.");
			return $this->render('ajax');
		}
		
		// Initialoise some variables
		$errors = false;
		$itemsRelisted = array();
		
		$ebay = new Ebay_Client();
		$Items = new Items(); // Load the Items Model
		$Status = new Status();
		
		foreach($data['listings'] as $id)
		{
	        //Check if the ID was provided and if it is an int
	        if(Zend_Validate::is($id, 'Int'))
	        {
				
				$item = $Items->getItem($id);
				
				if($item['status'] == 2 && $item['relist'] == 0)
				{
					$response = $ebay->relistItem($item);
					/*
					try {
						
					} catch (Exception $e) {
						$errors = true;
						var_dump($e);
						continue;
					}
					*/
					$status = $Status->getItemById($id);

					// Update the listing
					$status->submitted = $response->StartTime;
					$status->finishes = $response->EndTime;	
					$status->relist = 1;
			
					// Save the listings new status
					$status->save();
					
					
					$itemsRelisted[] = array('id' => $id, 
											 'fees' => $this->processFees($response),
											 'submitted' => $status->submitted,
											 'finishes' => $status->finishes,
											 'relist' => 1,
											 'status' => 1);
				}
			}
		// End For loop
		}
		$this->view->data = array('status' => true, 'listings' => $itemsRelisted);
		
		if($errors)
		{
			$this->view->data['message'] = "Some listings may not have been relisted";
			
			if(sizeof($itemsRelisted) == 0)
			{
				$this->view->data['status'] = false;
			}
		}
		
		return $this->render('ajax');
	}
	
	function sendinvoiceAction()
	{
		$data = $this->_request->getPost('json', 'false');		
        $data = Zend_Json::decode($data);
		
		if(!$data)
		{
			$this->view->data = array('status' => false, 'message' => "An invalid request was made");
		}
		
		
	}
	
	function getbuyerdetailsAction()
	{
		$data = $this->_request->getPost('json', 'false');
        $data = Zend_Json::decode($data);
		
		if(!$data || !is_array($data) || !is_array($data['listings']))
		{			
			$this->view->data = array('status' => false, 'message' => "An Invalid request has been made.");
			return $this->render('ajax');
		}
		
		$Items = new Items();
		$Status = new Status();
		$Transactions = new Transactions();
		$Buyers = new Buyers();
		
		$buyersList = array();
		foreach($data['listings'] as $id)
		{
	        //Check if the ID was provided and if it is an int
	        if(Zend_Validate::is($id, 'Int'))
	        {
				$item = $Items->getBasicItem($id);
				if(!$item)
				{
					continue;
				}
				//$select = $this->_db->select();
				$status = $Status->getItemById($item->id);
				
				if(!$status || $status->status < 3)
				{
					continue;
				}
				$transactions = $Transactions->getByEbayId($status->ebayId);
				$buyer = $Buyers->getByEbayUid($transactions->ebayUid);
				
				$buyersList[] = array('id' => $id, 'buyer' => $buyer->toArray());		
			}
		}
		$this->view->data = array('status' => true, 'buyers' => $buyersList);
		return $this->render('ajax');
	}
	function markAction()
	{
		
		$mark = $this->_request->getParam('arg1', false);
		$id = $this->_request->getParam('arg2', false);
			
		//Check if the ID was provided and if it is an int
		if(Zend_Validate::is($id, 'Int'))
		{
			$Items = new Items();
			$item = $Items->getItem($id);
			
			if(!$item || $item['status'] < 3)
			{
				$this->view->data = array('status' => false, 'message' => "The listing submitted is invalid");
				return $this->render('ajax');
			}
			
			$Transaction = new Transactions();			
			$transaction = $Transaction->getByEbayId($item['ebayId']);
			
			if(!$transaction)
			{
				$this->view->data = array('status' => false, 'message' => "The item doesn't have any transactions");
				return $this->render('ajax');
			}
			
			$Status = new Status();
			$status = $Status->getByEbayId($item['ebayId']);
			$listing = array();
			switch($mark)
			{				
				case 'paid': 
					/*
					$paidby = $this->_request->getPost('paymentMethod', false);
					
					if(!$paidby || !in_array($paidby, Ebay_Codes::get('BuyerPaymentMethod')))
					{
						$this->view->data = array('status' => false, 'message' => "The payment method is not valid");
						return $this->render('ajax');
					}
					*/
					
					if($transaction->status > 1)
					{
						$this->view->data = array('status' => false, 'message' => 'This item has already been paid for"');
						return $this->render('ajax');
					}
						
					$ebay = new Ebay_client();	
					
					// Not sure whether it is needed now
					//$ebay->reviseCheckoutStatus($item['ebayId'], 'Complete', array('TransactionID' => 0, 'PaymentMethodUsed' => $paidby, 'PaymentStatus' => 'Paid'));					
					$ebay->completeSale(0, $item['ebayId'], array('Paid' => true));

					
					$transaction->status = 2;						
					$transaction->save();
					
					//Only usable on chinese listings
					$status->status = 4;					
					$status->save();
					
					$listing = array('id' => $id, 'status' => $status->status);
				break;
				case 'dispatched':
					if($transaction->status != 2)
					{
						$this->view->data = array('status' => false, 'message' => 'Please make sure the item has been paid for."');
						return $this->render('ajax');
					}
					$ebay = new Ebay_client();
					$ebay->completeSale(0, $item['ebayId'], array('Shipped' => true));
					
					$transaction->status = 3;

					//Only usable on chinese listings					
					$status->status = 5;
					
					$status->save();
					$transaction->save();
					
					$listing = array('id' => $id, 'status' => $status->status);
					
				break;
				default:
				$this->view->data = array('status' => true, 'message' => 'Invalid request  was made');
				return $this->render('ajax');
			}
			$this->view->data = array('status' => true, 'listing' => $listing);
			return $this->render('ajax');
		}
	}
	
	function submitAction()
	{
		$mode = $this->_request->getParam('arg1', false);
		
		$data = $this->_request->getPost('json', 'false');		
        $data = Zend_Json::decode($data);
		
		// Check if the listings provided are valid
		if(!$mode || !$data || !is_array($data) || !is_array($data['listings']))
		{			
			$this->view->data = array('status' => false, 'message' => "An Invalid request has been made.");
			return $this->render('ajax');
		}
		
		$warnings = array();
		$fees = array();
		$listings = array();

		// Initialise the models
		$Status = new Status();
		$Items = new Items();
		
		foreach($data['listings'] as $id)
		{
	        //Check if the ID was provided and if it is an int
	        if(Zend_Validate::is($id, 'Int'))
	        {				
				$item = $Items->getItem($id);

				// Only allow the item to be submitted if it hasn't been submitted before, or has already been relisted and not sold
				if($item && ( $item['status'] == 0 || ($item['status'] == 2 && $item['relist'] == 1) ) )
				{
					try
					{
						$result = $this->submitListing($id, ($mode == 'confirm') ? false : true);
					} catch (Ebay_Exception $e)
					{
						// An Exception Occured
						$warnings[] = array('id' => $id, 'message' => $e->getMessage());
						continue;
					}
					
					if($mode == 'confirm')
					{
						$listings[] = $Items->getItem($id);
					}
					else
					{				
						//Just return the fees
						$fees[] = array($id, $result);					
					}
				}
				else
				{
					$warnings[] = array('id' => $id, 'message' => "This item cannot be submitted");
					continue;
				}
			}
		}
		
		$this->view->data = array('status' => true, 'warnings' => $warnings, 'fees' => $fees, 'listings' => $listings);
		return $this->render('ajax');
	}
	
    function removeAction()
    {
		$data = $this->_request->getPost('json', 'false');
        $data = Zend_Json::decode($data);
		
		if(!$data || !is_array($data) || !is_array($data['listings']))
		{			
			$this->view->data = array('status' => false, 'message' => "An Invalid request has been made.");
			return $this->render('ajax');
		}
		
		// Initialoise some variables
		$errors = false;
		$itemsRemoved = array();
		
		foreach($data['listings'] as $id)
		{
	        //Check if the ID was provided and if it is an int
	        if(Zend_Validate::is($id, 'Int'))
	        {
				/*
			             * Locate the entry in the database and check if it belongs to the user
			             * then proceed to delete
			             */
	            
	            $Items = new Items(); // Load the items model
	            $row = $Items->getBasicItem($id);
				
	            if($row) //The row uid doesn't belong to the currently authenticated user
	            {
					// Remove all images associated with the listing, and delete of the filespace
	                $Images = new Images();
	                $Images->removeImagesById($id);

	                $row->delete(); //Delete the row from the database.

	                $itemsRemoved[] = $id;
	            }
	            else
	            {
					$error = true;
	            }
	        }
	        else
	        {
	            $errors = true;		
	        }
			// End for loop
		}
		$this->view->data = array('status' => true, 'itemsRemoved' => $itemsRemoved);

		if($errors)
		{
			$this->view->data['message'] = "Some listings may not have been removed";
			
			if(sizeof($itemsRemoved) == 0)
			{
				$this->view->data['status'] = false;
			}
		}
		return $this->render('ajax');
    }
}